import urllib,urllib2,re,xbmcplugin,xbmcgui,os,time,sys
import plugin_helper

class NickoldeonManager:
  
  smallImgPat="""<div class="vitem mb37 right.*?">
			<div class="right imgdiv141">
		  <a href=".*?" style="display: block; font\-size: 1px; position: relative" class="right imgdiv141 block oflow zoom1"  >
			<img src="http://iscWBE.walla\.co\.il/w9/v/vod/play_btn_small\.gif" style="margin\-top: 59px; margin\-right: 117px; z\-index:1; position: relative;">
			<img src="(.*?)" alt="" title="" class="absolute" style="right: 0px; z\-index:0;">
		  </a>
		</div>
			<div style="margin\-top:8px;">
				<div class="title w3b"><a href="(.*?)" >(.*?)</a></div>
				<div class="hsubtitle oflow w2"><a href=".*?" >(.*?)</a></div>""".replace("\n","").replace("\t","").replace("\r","")
  
  smallImgPatJr="""			<img src="(http://mscWBE\.walla\.co\.il/.*?)" alt="" title="" class="absolute imgdiv141" style="right: 0px; z-index:0;">
			<img src="http://iscWBE\.walla\.co\.il/w9/v/vod/play_smal_lightblue\.gif" style="margin-top: 59px; margin-right: 117px; z-index:1; position: relative;">
		  </a>
		</div>
			<div style="margin-top:8px;">
				<div class="title w4b"><a href="(\?w=//\d+)" >(.*?)</a></div>
				<div class="hsubtitle oflow w3"><a href="\?w=//\d+" >(.*?)</a></div>
""".replace("\n","").replace("\t","").replace("\r","")
  
  bigImgPat = '"imgdiv301 imgcls" .*? src="(.*?)".*?<div class="title w5b mt5"><a href="(.*?)" >(.*?)</a></div><div class="hsubtitle oflow w3 mb5">(.*?)</div>'
  
  def __init__(self):
    self.MODES=plugin_helper.enum(GET_SERIES_LIST=1,GET_EPISODES_LIST=2,PLAY=3)
  
  def work(self,mode,url='',name=''):
    if (mode==self.MODES.GET_SERIES_LIST):
      self.getSeriesList()
    elif(mode==self.MODES.GET_EPISODES_LIST):
      self.getEpisodeList(url,name)
    elif(mode==self.MODES.PLAY):
      plugin_helper.playRtmpFromUrl(url)
      
  def getSeriesList(self):
    matches = plugin_helper.getMatches("http://nick.walla.co.il/",'<a class="w2 fclr2" href="(.*?/\?w=//\d+)">(.*?)</a>')
    for url,name in matches:
      if not url.startswith("http://"):
        url = "http://nick.walla.co.il"+url
      imgPath = plugin_helper.getPath('cache','headers','nickoldeon',name+".png")
      if not os.path.exists(imgPath):
        imgPath = "DefaultFolder.png"
      plugin_helper.addDir('Nickoldeon',name,url,2,{"Title": urllib.unquote(name)},imgPath)
    xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
    
  def getEpisodeList(self,url,name):
    data = plugin_helper.getData(url).replace("\n","").replace("\t","").replace("\r","")
    
    imgPath = plugin_helper.getPath('cache','headers','nickoldeon',name+".png")
    if (not os.path.exists(imgPath) or (time.time()-os.path.getmtime(imgPath))/60/60/24 > 7):    
      headerPath = re.compile('(http://iscWBE.walla.co.il/w9/skins/nick(_jr)?/\d+/header_pic_\d+.png)').findall(data)
      urllib.urlretrieve(headerPath[0][0],imgPath)#download the header picture for the next time
    
    fullEpisodesUrl = re.compile('" topbrd"></div><a href="(\?w=//\d+)" class="in_blk channel " onclick="Evt\(this,\d,&quot;\xf4\xf8\xf7\xe9\xed \xee\xec\xe0\xe9\xed&quot;').findall(data)
    
    if len(fullEpisodesUrl)==0: #check for movie
      movieurl = re.compile('<a href="(\?w=//\d+)" class="in_blk channel  selected_channel w3b" onclick="Evt\(this,\d,&quot;\xe4\xf1\xf8\xe8 \xe1\xe0\xe5\xf8\xea \xee\xec\xe0').findall(data)
      if len(movieurl) > 0: #movie mode
          url = "http://nick.walla.co.il/" + movieurl[0] + "/@@/video/flv_pl"
          print(url)
          plugin_helper.playRtmp("rtmp://waflaWBE.walla.co.il/vod/",plugin_helper.getMatches(url,"<src>mp4:(.*?)</src>")[0])
          return
          
    if len(fullEpisodesUrl)>0 and not url.endswith(fullEpisodesUrl[0]):
      url = "http://nick.walla.co.il/"+fullEpisodesUrl[0]
      data = plugin_helper.getData(url).replace("\n","").replace("\t","").replace("\r","")
    
    matches  = re.compile(self.bigImgPat).findall(data)      
    matches += re.compile(self.smallImgPat).findall(data)
    if (len(matches)<=2):
        print("JR MODE!")
        matches += re.compile(self.smallImgPatJr).findall(data)
        self.smallImgPat = self.smallImgPatJr
        
    matches += self.getMoreFromAjax(url)
    for pic,href,title,subtitle in matches:
      plugin_helper.addVideo('Nickoldeon',name,subtitle,'http://nick.walla.co.il/'+href,3,{ "Title": urllib.unquote(title),"Tagline":urllib.unquote(subtitle)},pic)
      
    
    xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
    
    for x in range(1,29):
      xbmcplugin.addSortMethod(int(sys.argv[1]),x)


  
  def getMoreFromAjax(self,url):
    match=[]
    length = 1
    i=2
    url = url + '&page='
    while (length>0 and i<=10):
      print(url+str(i))
      news = plugin_helper.getMatches(url+str(i),self.bigImgPat,True)
      news += plugin_helper.getMatches(url+str(i),self.smallImgPat,True)
      length=len(news)
      print(length)
      match+=news
      i+=1
    return match
    